/**
 *  Copyright (C) 2011  Thomas ROBIN
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package triseries;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;

/**
 * @author tshepo
 * 
 */
public class Main {

	public static boolean debug = false;
	private static int min, sec;
	public static Image iconWait = java.awt.Toolkit.getDefaultToolkit()
			.getImage(Main.class.getResource("/icones/play.png"));
	public static Image iconBusy = java.awt.Toolkit.getDefaultToolkit()
			.getImage(Main.class.getResource("/icones/busy-icon0.gif"));
	public static Image iconError = java.awt.Toolkit.getDefaultToolkit()
			.getImage(Main.class.getResource("/icones/bnk.gif"));
	private static Image iconStop = java.awt.Toolkit.getDefaultToolkit()
			.getImage(Main.class.getResource("/icones/!.gif"));
	private static Image previousIcon;
	private static boolean error = false;
	private static TrayIcon trayIcon;
	private static ActionListener al;
	public static MyJPopupMenu jpopup = null;

	public static void main(String[] args) {
		if (!MyProperties.init()) {
			if (SystemTray.isSupported()) {

				trayIcon = new TrayIcon(iconStop, "TriSeries", null);
				trayIcon.setImageAutoSize(true);
				trayIcon.addActionListener(new ActionListener() {

					public void actionPerformed(ActionEvent e) {
						FileAcces.openProperties();
						System.exit(0);

					}
				});
				try {
					SystemTray.getSystemTray().add(trayIcon);
				} catch (AWTException e1) {
					e1.printStackTrace();
					System.out
							.println("Ajouter votre login et mot de passe au fichier Settings.");
					return;
				}
				trayIcon
						.displayMessage(
								"TriSeries",
								"Vous devez ajouter votre login et mot de passe au fichier Settings.",
								TrayIcon.MessageType.WARNING);

				return;
			}
			System.out
					.println("Ajouter votre login et mot de passe au fichier Settings.");
			return;
		}

		if (!MyProperties.noUI && SystemTray.isSupported()) {

			try {
				UIManager.setLookAndFeel(UIManager
						.getSystemLookAndFeelClassName());
			} catch (ClassNotFoundException ex) {
				processExeption("UIManager.setLookAndFeel :\n" + ex.getStackTrace().toString());
			} catch (InstantiationException ex) {
				processExeption("UIManager.setLookAndFeel :\n" + ex.getStackTrace().toString());
			} catch (IllegalAccessException ex) {
				processExeption("UIManager.setLookAndFeel :\n" + ex.getStackTrace().toString());
			} catch (UnsupportedLookAndFeelException ex) {
				processExeption("UIManager.setLookAndFeel :\n" + ex.getStackTrace().toString());
			}

			trayIcon = new TrayIcon(iconBusy, "TriSeries", null);
			trayIcon.setImageAutoSize(true);

			jpopup = new MyJPopupMenu();

			al = new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					if (error) {
						FileAcces.openFile("err.log");
						error = false;
						trayIcon.setImage(previousIcon);
						trayIcon.setToolTip("TriSeries");
					} else {
						JOptionPane
								.showMessageDialog(null,
										"TriSeries\nCette application fonctionne grâce a l'API de betaseries.com");

					}

				}
			};

			trayIcon.addActionListener(al);

			trayIcon.addMouseListener(new MouseListener() {

				public void mouseClicked(MouseEvent e) {
					if (e.getButton() == MouseEvent.BUTTON3) {
						jpopup.setInvoker(jpopup);
						jpopup.setVisible(true);
						jpopup.setLocation(trayIcon, e);

					}
				}

				public void mousePressed(MouseEvent e) {
				}

				public void mouseReleased(MouseEvent e) {
				}

				public void mouseEntered(MouseEvent e) {
				}

				public void mouseExited(MouseEvent e) {
				}
			});

			trayIcon.setImageAutoSize(true);

			try {
				SystemTray.getSystemTray().add(trayIcon);
			} catch (AWTException e2) {
				processExeption("Main.main :\n" + e2.getStackTrace().toString());
			}

			min = 1;
			sec = 0;
			while (true) {
				while (min-- > 0) {
					while (sec-- > 0) {

						try {
							Thread.sleep(1000);
						} catch (InterruptedException e1) {
							processExeption("Main.main :\n" + e1.getStackTrace().toString());
						}
						jpopup.UpdateTiming(min, sec);

					}
					sec = 60;
				}
				BetaSeriesXML.openConnection();

				if (!error) {
					trayIcon.setImage(iconBusy);
				}
				Scan t = new Scan();
				t.start();

				jpopup.startBusyIcon();

				try {
					t.join();
				} catch (InterruptedException e1) {
					processExeption("Main.main :\n" + e1.getStackTrace().toString());
				}

				List<Element> unwatched = new ArrayList<Element>(BetaSeriesXML
						.getUnWatched());

				jpopup.Update(unwatched);
				min = MyProperties.time;
				if (error) {
					previousIcon = iconWait;
				} else {
					trayIcon.setImage(iconWait);
				}
			}
		}
		if (!SystemTray.isSupported()) {
			System.err.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
					.format(Calendar.getInstance().getTime()));
			System.err.println("System Tray is not supported in this system");
		}
		min = MyProperties.time;
		while (true) {

			if ((new File("Settings.txt")).lastModified() > MyProperties.lastmodif)
				MyProperties.init();
			Scan t = new Scan();
			t.start();

			try {
				Thread.sleep(min * 60000);
			} catch (InterruptedException e) {
				processExeption("Main.main :\n" + e.getStackTrace().toString());
			}
		}

	}

	static void nowAction() {
		min = sec = 0;
	}

	public static void processExeption(String s) {
		System.err.println("Erreur - "
				+ (new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")).format(Calendar
						.getInstance().getTime()));
		System.err.println(s);
		if (!error) {
			error = true;
			previousIcon = trayIcon.getImage();
			trayIcon.setImage(iconError);
			trayIcon
					.setToolTip("double cliquez sur l'icone pour afficher les erreurs");
		}
	}

	static void processWarning(String s) {
		System.err.println("Warning - "
				+ (new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")).format(Calendar
						.getInstance().getTime()));
		System.err.println(s);
	}

}
